<template>
  <view class="page">
    <view class="top-img" style="padding-bottom: 20rpx;">
      <image :src="data_info.cover" mode="widthFix" class="hero-pic"></image>
      <view class="title">{{data_info.sbflmc}}</view>
    </view>

    <view class="rent-card" style="margin-top: 40rpx;">
      <view class="seg">
        <view :class="['seg-item', mode==='ziti'?'active':'']" @tap="switchMode('ziti')">
          站点自提 <view class="seg-active-cap" v-if="mode==='ziti'" style="display: none;"></view>
        </view>
        <view :class="['seg-item', mode==='peisong'?'active':'']" @tap="switchMode('peisong')">
          配送上门 <view class="seg-active-cap" v-if="mode==='peisong'" style="display: none;"></view>
        </view>
      </view>

      <view class="time-row" @tap="showCalendar = true" style="margin-top: 20rpx;">
        <view class="time-col">
          <text class="time-sub">周{{ weekdayText(startDate) }}{{ isToday(startDate) ? '（今天）' : '' }}</text>
          <text class="time-main">{{ mdText(startDate) }}</text>
        </view>
        <view class="time-center"><text class="time-center-text">{{ rentDays }}天</text></view>
        <view class="time-col right">
          <text class="time-sub">周{{ weekdayText(endDate) }}</text>
          <text class="time-main">{{ mdText(endDate) }}</text>
        </view>
      </view>

      <view class="quick-days">
        <view v-for="d in [7,14,21,30]" :key="d"
          :class="['qd', rentDays===d ? 'qd-active' : '']"
          @tap.stop="applyQuickDays(d)">{{ d }}天</view>
      </view>

      <view class="pill"><text class="pill-label">押　金：</text><text class="pill-value strong">{{ deposit }}元</text></view>
      <view class="pill"><text class="pill-label">租　金：</text><text class="pill-value strong">{{ rent }}元</text></view>
	 <view class="pill" v-if="mode==='peisong'">
		 <text class="pill-label">配送费：</text>
		 <text class="pill-value strong">{{ peisong_money*2 }}元</text>
		</view>
	  <!-- 配送说明 -->
	  <view class="pill-tip" v-if="mode==='peisong'">
	    * 单程{{ peisong_money }}元，往返费用一次性收取
	  </view>
      <view class="pill"><text class="pill-label">名　字：</text><input class="pill-input" v-model="form.name" placeholder="请输入您的名字" /></view>
      <view class="pill"><text class="pill-label">联系电话：</text><input class="pill-input" v-model="form.mobile" type="number" maxlength="11" placeholder="请输入您的电话" /></view>

      <view v-if="mode==='ziti'" class="station-wrap">
        <view class="station-hd">
          <text class="pill-label">附近站点：</text>
          <text class="iconfont icon-you" @tap="openStationSelector"></text>
        </view>
        <view class="station-card">
          <view class="left">
            <view class="row1"> <image class="pin" 
         src="https://kehu-1256834579.cos.ap-shanghai.myqcloud.com/weier/dingwei.png" 
         mode="widthFix" /><text class="name">{{ curStation.name }}</text></view>
            <view class="row2"><text class="dist">{{ curStation.distanceText }}</text></view>
          </view>
          <view class="right">
            <view class="btn ghost" @tap.stop="callStation">联系电话</view>
            <view class="btn primary" @tap.stop="navToStation">导航</view>
          </view>
        </view>
      </view>

      <view v-else class="pill clickable" @tap="chooseLocation">
        <text class="pill-label">配送地址：</text>
        <text v-if="!form.addr" class="pill-placeholder">请选择地图位置并输入名称</text>
        <text v-else class="pill-value">{{ form.addr }}</text>
      </view>

      <view class="total" v-if="mode == 'peisong'">合计：<text class="money">￥{{total}}</text></view>
	  <view class="total" v-else>合计：<text class="money">￥{{ total }}</text></view>
    </view>
	   <!-- …上面的租赁卡片 rent-card 结束 -->
	    <view class="warm-box">
	      <view class="warm-title">温馨提示</view>
	      <view class="warm-text">
	        您可在用车前联系自提点预约取车，取车当日不计入租赁周期。
	      </view>
	    </view>	
	    <view class="footer">
	      <view class="kefu" @tap="contactCS">联系客服</view>
	      <button class="submit" @tap="sub_order()">提交订单</button>
	    </view>
    <view class="footer">
      <view class="kefu" @tap="contactCS">联系客服</view>
      <button class="submit" @tap="sub_order()">提交订单</button>
    </view>
	
    <!-- 时间控件联动：把当前天数/起止传进去 -->
   <rent-calendar
     :visible="showCalendar"
     :minDays="mode==='ziti'?1:3"
     :days="rentDays"
     :start="startDate"
     :end="endDate"
     @days-change="rentDays = $event"
     @close="showCalendar = false"
     @confirm="onCalendarConfirm"
   />
  </view>
</template>

<script>
import RentCalendar from '@/components/rent-calendar.vue'
import common_config from '../../static/js/common.js';
var config = common_config.config;
var that;	
var userInfo;
export default {
  components: { RentCalendar },
  data(){
    const now = new Date(); now.setHours(0,0,0,0)
    return {
	  rowId:'',
	  center:{},
	  data_info:{},
      heroImg:'https://kehu-1256834579.cos.ap-shanghai.myqcloud.com/weier/che1.png',
      mode:'ziti',
      startDate: now,
      endDate: new Date(now.getTime()+6*86400000),
      rentDays: 7,
	  peison_total:0,
      showCalendar: false,
	  zhouzu:0,
	  yuezu:0,
      deposit: 0,
      unitRent: 300/7,
	  peisong_money:'0.00',
      form:{ name:'', mobile:'', addr:'', lat: '', lng: ''  },
      stations:[
        //{ id:1, name:'服务商A', distance:'0.5km', phone:'13800000000', lat:31.23, lng:121.47 },
       // { id:2, name:'服务商B', distance:'0.9km', phone:'13900000000', lat:31.226, lng:121.45 }
      ],
      curStationIdx: 0
    }
  },
  onLoad(options) {
  	that = this;
  	that.rowId = options.rowid;
	that.center = uni.getStorageSync('location_center');
	//console.log(that.center);
	that.center = JSON.parse(that.center);
  	that.plusReady();
  },
  computed:{
    curStation(){ return this.stations[this.curStationIdx] || { name:'—', distance:'—' } },
    rent(){
		if(this.rentDays >= 30){
			return this.yuezu;
		}else{
			var num = parseInt(this.rentDays/7);
			if(this.mode == 'peisong'){
				
			}
			return this.zhouzu*num;
		}
		//return Math.ceil(this.unitRent * this.rentDays) 
	},
    total(){ 
		if(this.mode == 'peisong'){
			var r = common_config.accAdd(this.deposit,this.rent);
			//common_config.calert('test'+this.peisong_money+','+r);
			return common_config.accAdd(this.peisong_money*2,r);
			//return common_config.accAdd(this.deposit,this.rent) 
		}else{
			return common_config.accAdd(this.deposit,this.rent) 
		}
		
	}
  },
  methods:{
	  //初始化
	  plusReady(){
	    	userInfo = uni.getStorageSync('userInfo');
	    	if(userInfo){
	    		userInfo = JSON.parse(userInfo);
	    		that.if_login = true;
	    		that.member_profile = userInfo;
				that.load_datas();
				that.load_ziti_list();
	    	}else{
				uni.switchTab({
					url:'/pages/index/me'
				});
	    		that.if_login = false;
	    	}
	    	
	  },
	  load_datas(){
	  	//console.log(121212);
	  	uni.request({
	  	  url: config.request_url+'/v2/open/worksheet/getRowByIdPost',
	  	  method: 'POST',
	  	  header: {
	  		'Content-Type': 'application/json'
	  	  },
	  	  data: {
	  		"appKey": config.appKey,
	  		"sign": config.sign,
	  		"worksheetId": "czsbfl",
	  		"rowId":that.rowId
	  	  },
	  	  success: (res) => {
	  		//console.log('返回结果:', res.data);
	  		res = res.data;
	  		//console.log(res);
	  		if(res.success){
	  			that.data_info = res.data;
	  			var r = JSON.parse(res.data.tupian);
	  			var details = JSON.parse(res.data.xqtp);
	  			that.data_info.cover = r[0].original_file_full_path;
	  			that.data_info.details = details;
				that.deposit = res.data.yajin;
				that.yuezu = res.data.yzjfje;
				that.peisong_money = res.data.dcpsfy;
				that.zhouzu = res.data.zzjfje;
				
	  		}else{
	  			 uni.showToast({ title: res.data.msg || '数据获取失败', icon: 'none' });
	  		}
	  	  },
	  	  fail: (err) => {
	  		console.error('请求失败:', err);
	  		uni.showToast({ title: '网络错误', icon: 'none' });
	  	  }
	  	})  
	  },
	  load_ziti_list(){
	  	console.log(121212);
	  	uni.request({
	  	  url: config.request_url+'/v2/open/worksheet/getFilterRows',
	  	  method: 'POST',
	  	  header: {
	  		'Content-Type': 'application/json'
	  	  },
	  	  data: {
	  		"appKey": config.appKey,
	  		"sign": config.sign,
	  		"worksheetId": "ztdgl",
	  		"pageSize": 50,
	  		"pageIndex": 1,
			"filters": [
				{
					"controlId": "sfqy",
					"dataType": 11,
					"spliceType": 1,
					"filterType": 2,
					"value": "是"
				}
			]
	  	  },
	  	  success: (res) => {
	  		//console.log('返回结果:', res.data);
	  		res = res.data;
	  		//console.log(res);
	  		if(res.success){
	  			var ziti_list = res.data.rows;
				var arr = [];
				for(var i = 0;i < ziti_list.length;i++){
					var r = (ziti_list[i].jingweidu).split(',');
					arr.push({
						id:ziti_list[i].rowid,
						name:ziti_list[i].ztdmc,
						latitude:r[0],
						longitude:r[1],
						address:ziti_list[i].bgdz,
						phone:ziti_list[i].dianhua
						
					});
				}
				console.log(arr);
				arr = common_config.sortStationsByDistance(arr, that.center);
				console.log(arr);
				that.stations = arr;
				//console.log(that.stations);
	  		}else{
	  			 uni.showToast({ title: res.data.msg || '数据获取失败', icon: 'none' });
	  		}
	  	  },
	  	  fail: (err) => {
	  		console.error('请求失败:', err);
	  		uni.showToast({ title: '网络错误', icon: 'none' });
	  	  }
	  	})  
	  },
	  
	  toYmdHi(d){ const dt=new Date(d); const y=dt.getFullYear(); const m=(dt.getMonth()+1+'').padStart(2,'0'); const day=(dt.getDate()+'').padStart(2,'0'); const hh=(dt.getHours()+'').padStart(2,'0'); const mi=(dt.getMinutes()+'').padStart(2,'0'); return `${y}-${m}-${day} ${hh}:${mi}`; },
	  startOfDayYmdHi(d){ const t=new Date(d); t.setHours(0,0,0,0); return this.toYmdHi(t); },
	  endOfDayYmdHi(d){ const t=new Date(d); t.setHours(23,59,0,0); return this.toYmdHi(t); },
	  sub_order(){
	  	if(!this.form.name) return uni.showToast({title:'请输入姓名',icon:'none'})
	  	if(!/^\d{6,}$/.test(this.form.mobile)) return uni.showToast({title:'请输入正确的电话',icon:'none'});
		if(that.mode == 'peisong' && !that.form.addr){
			return uni.showToast({title:'请选择配送地址',icon:'none'});
		}
		const startTime = this.startOfDayYmdHi(this.startDate); // 例如 2025-09-29 00:00
		const endTime   = this.endOfDayYmdHi(this.endDate);     // 例如 2025-09-29 23:59
		var formData = {
	  		"appKey": config.appKey,
	  		"sign": config.sign,
	  		"worksheetId": "czsbfl",
	  		"CzsbflId":that.rowId,
			"UserId":userInfo.rowid,// 用户rowid
			"Type": that.mode == 'ziti' ? "自提" : "配送", // 订单类型  自提、配送
			"ZtdId":that.stations[that.curStationIdx].id,// 自提点rowid
			"StartTime":startTime, // 订单开始时间 00:00:00
			"EndTime":endTime, // 结束结束时间 23:59:59
			"Zlzqlx":that.rentDays >= 30 ? '月' : '周', // 租赁周期类型   周、月
			"Zlzqsl":that.rentDays >= 30 ? 1 : parseInt(that.rentDays/7), // 租赁周期数量  租赁周期类型是周的时候，7天传1，14天传2，21天传3。租赁周期类型是月的时候，1个月传1
			"Shrxm":that.form.name, // 收货人姓名
			"Shrlxdh":that.form.mobile, // 收货人联系电话
			"Shdz":"测试", // 收货地址
			"Shdz":that.form.addr,
			"lng":that.form.lng,
			"lat":that.form.lat
	  	  };
		  uni.showLoading({
		  	title:'正在提交订单...'
		  });
		  //console.log(formData);
		  //return false;
	  	//if(this.mode==='peisong' && !this.form.addr) return uni.showToast({title:'请选择配送地址',icon:'none'})
	  	uni.request({
	  	  url: config.request_url+'/workflow/hooks/NjhkNjVlZjRlNDg4Mzg3YmMxNTE2YjVj',
	  	  method: 'POST',
	  	  header: {
	  		'Content-Type': 'application/json'
	  	  },
	  	  data: formData,
	  	  success: (res) => {
			  uni.hideLoading();
	  		//console.log('返回结果:', res.data);
	  		res = res.data;
			res = res.data;
	  		
	  		if(res.success != 'false'){
	  			uni.redirectTo({
	  				url:'/pages/index/yuyue_to_pay?czddRowid='+res.data.czddRowid+'&yajinRowid='+res.data.yajinRowid+'&zujinRowid='+res.data.zujinRowid+'&rowid='+that.rowId
	  			})
	  		}else{
				common_config.calert(res.errorMsg);
	  			 uni.showToast({ title: res.data.msg || '数据获取失败', icon: 'none' });
	  		}
	  	  },
	  	  fail: (err) => {
	  		console.error('请求失败:', err);
	  		uni.showToast({ title: '网络错误', icon: 'none' });
	  	  }
	  	})  
	  },
    pad2(n){ return (''+n).padStart(2,'0') },
    mdText(d){ if(!d) return '--'; const dt=new Date(d); return `${this.pad2(dt.getMonth()+1)}月${this.pad2(dt.getDate())}日` },
    weekdayText(d){ if(!d) return ''; return ['日','一','二','三','四','五','六'][new Date(d).getDay()] },
    isToday(d){ if(!d) return false; const a=new Date(); a.setHours(0,0,0,0); const b=new Date(d); b.setHours(0,0,0,0); return a.getTime()===b.getTime() },

    applyQuickDays(d){
      this.rentDays = d
      const base = new Date(); base.setHours(0,0,0,0)
      if(this.mode==='peisong') base.setDate(base.getDate()+2) // 第3天起租
      this.startDate = base
      this.endDate = new Date(base.getTime() + (d-1)*86400000)
    },
    switchMode(m){ if(this.mode!==m){ this.mode=m; this.applyQuickDays(this.rentDays||7) } },

    openStationSelector(){
		uni.navigateTo({
		    url: '/pages/index/station_list',
		    success: (res) => {
		      // 传入当前站点数组
		      res.eventChannel.emit('sendStations', { stations: this.stations })
		    }
		  })
		
		  // 接收返回选择结果
		  uni.$once('stationSelected', (station) => {
		    const idx = this.stations.findIndex(s => s.id === station.id)
		    if (idx !== -1) this.curStationIdx = idx
		  });
	},
    callStation(){ const tel=this.curStation.phone||''; if(!tel) return uni.showToast({title:'无联系电话',icon:'none'}); uni.makePhoneCall({phoneNumber:tel}) },
    navToStation(){ const s=this.curStation; uni.openLocation({ latitude:parseFloat(s.latitude) ||31.23, longitude:parseFloat(s.longitude)||121.47, name:s.name, address:`距离 ${s.distance}` }) },
    chooseLocation(){ uni.chooseLocation({ success:(res)=>{ this.form.addr = res.address || res.name || `${res.latitude},${res.longitude}` } }) },

    onCalendarConfirm({ start, end, days }) {
      this.startDate = start
      this.endDate   = end
      this.rentDays  = days
    },

    contactCS(){ uni.showToast({title:'联系客服（示例）',icon:'none'}) },
    submit(){
      if(!this.form.name) return uni.showToast({title:'请输入姓名',icon:'none'})
      if(!/^\d{6,}$/.test(this.form.mobile)) return uni.showToast({title:'请输入正确的电话',icon:'none'})
      if(this.mode==='peisong' && !this.form.addr) return uni.showToast({title:'请选择配送地址',icon:'none'})
      uni.showToast({title:'提交成功（模拟）',icon:'success'})
    }
  }
}
</script>

<style lang="scss" scoped>
.page{ background:#f6f6f6; min-height:100vh; padding-bottom:160rpx; }
.top-img{ width:100%; background:#E8E8E8; padding:40rpx 0 60rpx; text-align:center; }
.hero-pic{ width:42%; }
.title{ margin-top:12rpx; text-align:center; color:#222; font-size:28rpx; }

.rent-card{ margin:-80rpx 24rpx 24rpx; background:#fff; border-radius:28rpx; padding:20rpx 22rpx 10rpx; box-shadow:0 8rpx 24rpx rgba(0,0,0,.06); }

/* 分段 */
.seg{ display:flex; background:#f1f3f5; border-radius:22rpx; padding:6rpx; position:relative; margin:4rpx 0 16rpx; }
.seg-item{ flex:1; text-align:center; padding:20rpx 0; font-size:28rpx; color:#8a8f97; position:relative; border-radius:18rpx; }
.seg-item.active{ background:#fff; color:#1f2329; font-weight:700; }
.seg-active-cap{ position:absolute; bottom:-6rpx; left:50%; transform:translateX(-50%); width:120rpx; height:20rpx; background:#fff; border-bottom-left-radius:20rpx; border-bottom-right-radius:20rpx; }

/* 时间行 */
.time-row{ background:#f7f8fa; border-radius:22rpx; padding:22rpx 20rpx; display:flex; align-items:center; justify-content:space-between; }
.time-col{ width:42%; }
.time-col.right{ text-align:right; }
.time-sub{ display:block; color:#8a8f97; font-size:24rpx; }
.time-main{ display:block; color:#1f2329; font-size:34rpx; font-weight:800; margin-top:8rpx; }
.time-center{ width:16%; display:flex; align-items:center; justify-content:center; }
.time-center-text{ color:#8a8f97; font-size:26rpx; }

/* 快捷天数 */
.quick-days{ display:flex; gap:16rpx; margin:18rpx 4rpx 8rpx; flex-wrap:wrap; }
.qd{ min-width:120rpx; text-align:center; padding:12rpx 0; border-radius:999rpx; border:2rpx solid #DDE1E6; background:#fff; color:#6d7785; font-size:26rpx; }
.qd-active{ background:#0a67b8; color:#fff; border-color:#0a67b8; }

/* 胶囊行 */
.pill{ margin:14rpx 4rpx 0; padding:24rpx 26rpx; background:#f7f8fa; border-radius:999rpx; display:flex; align-items:center; }
.pill-label{ width:170rpx; color:#6c727a; font-size:28rpx; }
.pill-value{ flex:1; color:#1f2329; font-size:28rpx; }
.pill-input{ flex:1; color:#1f2329; font-size:28rpx; }
.pill-placeholder{ flex:1; color:#bfc5cd; font-size:28rpx; }
.strong{ font-weight:800; }
.clickable{ cursor:pointer; }

/* 站点卡片 */
.station-wrap{ margin-top:14rpx; }
.station-hd{ display:flex; align-items:center; justify-content:space-between; padding:0 6rpx 10rpx; }
.station-hd .arrow{ color:#9aa1a9; font-size:28rpx; }
.station-hd .iconfont{font-size: 42rpx;}
.station-card{ display:flex; justify-content:space-between; align-items:center; background:#f7f8fa; border-radius:20rpx; padding:18rpx; }
.station-card .left{ display:flex; flex-direction:column; gap:8rpx; }
.row1{ display:flex; align-items:center; gap:8rpx; }
.pin {
  width: 30rpx;
  height: 30rpx;
  display: inline-block;
}
.name{ font-size:30rpx; color:#1f2329; font-weight:700; }
.row2 .dist{ display:inline-block; font-size:22rpx; padding:6rpx 10rpx; background:#e9f4ff; color:#0a67b8; border-radius:10rpx; }
.station-card .right{ display:flex; gap:12rpx; }
.btn{ min-width:156rpx; text-align:center; padding:16rpx 18rpx; border-radius:14rpx; font-size:26rpx; }
.btn.ghost{ background:#eef2f5; color:#3b3f45; }
.btn.primary{ background:#0a67b8; color:#fff; }

/* 合计 */
.total{ text-align:right; padding:18rpx 6rpx 6rpx; font-size:30rpx; }
.money{ color:#ff2d2d; font-weight:800; }

/* 底部操作条 */
.footer{ position:fixed; left:0; right:0; bottom:0; background:#fff; display:flex; align-items:center; border-top:1rpx solid #eee; padding-bottom:env(safe-area-inset-bottom); }
.kefu{ width:28%; text-align:center; padding:24rpx 0; font-size:28rpx; color:#2d2f33; }
.submit{ flex:1; margin:12rpx 12rpx 12rpx 0; height:92rpx; line-height:92rpx; text-align:center; background:#0a67b8; color:#fff; border-radius:16rpx; font-size:32rpx; font-weight:800; }

.warm-box{
  margin: 18rpx 24rpx 0;
  background: #f2f5f8;
  border-radius: 20rpx;
  padding: 22rpx 24rpx;
  text-align: center;
}
.warm-title{
  color:#0a67b8;
  font-size: 28rpx;
  font-weight: 700;
  margin-bottom: 8rpx;
}
.warm-text{
  color:#6f757d;
  font-size: 24rpx;
  line-height: 1.6;
}
.pill-tip {
  margin: 8rpx 6rpx 0;
  padding-left: 26rpx;
  font-size: 24rpx;
  color: #8a8f97;
}
</style>
